//
//  RCMerchantCommitWrongInfoViewController.m
//  RocketProject
//
//  Created by Wu Chengwei on 13-9-4.
//  Copyright (c) 2013年 Rocket. All rights reserved.
//

#import "RCMerchantCommitWrongInfoViewController.h"
#import "CommonDefines.h"
#import "UIColor-Expanded.h"
#import "TTTAttributedLabel.h"
#import "AppDelegate.h"
#import "GloableEngineService.h"
#import "RCFeedbackDataModel.h"
#import "FrameworkRelativeDefines.h"


#define kLeftButtonImageFile       @"image_merchant_commit_wrong_leftButton.png"
#define kRightButtonImageFile    @"image_merchant_commit_wrong_rightButton.png"
#define kLineImageFile           @"image_line_type3.png"
#define kFormImageFile           @"image_merchant_commit_form.png"
#define kButtonImageFile         @"login_btn.png"


#define kTextViewHolderStr      @"请输入错误信息反馈的意见(600子以内)"

#define kMaxWordCount           600

@interface RCMerchantCommitWrongInfoViewController ()

@property(nonatomic,copy) NSString *merchantID;
@property(nonatomic,copy) NSString *merchantName;
@property(nonatomic,retain)UIButton *leftButton;
@property(nonatomic,retain)UIButton *rightButton;
@property(nonatomic,retain)UITextView *contentTextView;
@property(nonatomic,retain)UITextField *contentTextField;
@property(nonatomic,retain)UIButton *commitButton;
@property(nonatomic,retain)UILabel *wordCountLabel;
@property(nonatomic,retain)MBProgressHUDEx *progressHub;
@property(nonatomic,assign)int64_t requestID;

@end

@implementation RCMerchantCommitWrongInfoViewController

@synthesize merchantID = _merchantID;
@synthesize merchantName = _merchantName;
@synthesize leftButton = _leftButton;
@synthesize rightButton = _rightButton;
@synthesize contentTextField = _contentTextField;
@synthesize contentTextView = _contentTextView;
@synthesize commitButton = _commitButton;
@synthesize wordCountLabel = _wordCountLabel;
@synthesize progressHub = _progressHub;
@synthesize requestID = _requestID;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

-(id)initWithMerchantName:(NSString *)merchantID withName:(NSString *)merchantName{
    self = [super init];
    if (self) {
        self.merchantID = merchantID;
        self.merchantName = merchantName;
        [self initKeyBoard];
    }
    return self;
}

-(void)initKeyBoard{
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillChangeFrameNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
}

-(void)dealloc{
    [[IManager sharedInstance]cancelFetchDataRequestByRequestID:_requestID];
    _requestID = kInvalidRequestId;
    
    [[NSNotificationCenter defaultCenter]removeObserver:self];
    
    self.progressHub.delegate = nil;
    self.progressHub = nil;
    self.merchantID = nil;
    self.merchantName = nil;
    self.leftButton = nil;
    self.rightButton = nil;
    self.contentTextView = nil;
    self.contentTextField = nil;
    self.commitButton = nil;
    self.wordCountLabel = nil;
    [super dealloc];
}

-(void)loadView{
    [super loadView];
    _leftButton = [[UIButton alloc]initWithFrame:CGRectMake(0, 0, 44, 44)];
    [_leftButton setImage:[UIImage imageNamed:kLeftButtonImageFile]
                  forState:UIControlStateNormal];
    [_leftButton setImage:[UIImage imageNamed:kLeftButtonImageFile]
                  forState:UIControlStateHighlighted];
    [_leftButton addTarget:self action:@selector(leftButtonClicked) forControlEvents:UIControlEventTouchUpInside];
    self.navigationItem.leftBarButtonItem = [self createLeftBarButtonItemWithButton:_leftButton];
    
    _rightButton = [[UIButton alloc]initWithFrame:CGRectMake(0, 0, 44, 44)];
    if ([[[UIDevice currentDevice]systemVersion]floatValue] >=7.0) {
        _rightButton.frame = CGRectMake(10, 0, 44, 44);
    }
    [_rightButton setImage:[UIImage imageNamed:kRightButtonImageFile]
                 forState:UIControlStateNormal];
    [_rightButton setImage:[UIImage imageNamed:kRightButtonImageFile]
                 forState:UIControlStateHighlighted];
    [_rightButton addTarget:self action:@selector(commitButtonClicked) forControlEvents:UIControlEventTouchUpInside];
    _rightButton.enabled = NO;
    self.navigationItem.rightBarButtonItem = [self createLeftBarButtonItemWithButton:_rightButton];
    
    self.navigationItem.titleView = [self createTwolineTitleView];
    
}

-(UIView *)createTwolineTitleView{
    UIView *titleView = [[[UIView alloc]initWithFrame:CGRectMake(0, 0, 150, 44)]autorelease];
    UILabel *upperLabel = [[UILabel alloc]initWithFrame:CGRectMake(0, 5, 150, 15)];
    upperLabel.backgroundColor = [UIColor clearColor];
    upperLabel.textColor = [UIColor whiteColor];
    upperLabel.textAlignment = UITextAlignmentCenter;
    upperLabel.font = [UIFont fontWithName:kFontNameHeiti size:15];
    upperLabel.shadowColor = [UIColor colorWithHex:0xff2c2c2];
    upperLabel.shadowOffset = CGSizeMake(0, 0.5);
    upperLabel.text = @"其他错误";
    [titleView addSubview:upperLabel];
    [upperLabel release];
    
    UILabel *downLabel = [[UILabel alloc]initWithFrame:CGRectMake(0, 24, 150, 15)];
    downLabel.backgroundColor = [UIColor clearColor];
    downLabel.textColor = [UIColor whiteColor];
    downLabel.textAlignment = UITextAlignmentCenter;
    downLabel.font = [UIFont fontWithName:kFontNameHeiti size:15];
    downLabel.shadowColor = [UIColor colorWithHex:0xff2c2c2];
    downLabel.shadowOffset = CGSizeMake(0, 0.5);
    downLabel.text = self.merchantName;
    [titleView addSubview:downLabel];
    [downLabel release];
    return titleView;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    
	// Do any additional setup after loading the view.
    TTTAttributedLabel *infoLabel = [[TTTAttributedLabel alloc]initWithFrame:CGRectMake(13, 15, 294, 46)];
    infoLabel.backgroundColor = [UIColor clearColor];
    infoLabel.textColor = [UIColor colorWithHex:0xff505050];
    infoLabel.font = [UIFont fontWithName:kFontNameLightHeiti size:16];
    infoLabel.numberOfLines = 2;
    infoLabel.verticalAlignment = TTTAttributedLabelVerticalAlignmentTop;
    infoLabel.leading = 3;
    infoLabel.text = @"感谢您报告商户的错误信息，我们会将回复邮件发送至您填入的Email中";
    [self.viewContainer addSubview:infoLabel];
    [infoLabel release];
    
    UIImageView *lineImageView = [[UIImageView alloc]initWithFrame:CGRectMake(0, 61, 320, 1)];
    UIImage *lineImage = [UIImage imageWithContentsOfFile:[[NSBundle mainBundle]pathForResource:kLineImageFile ofType:nil]];
    [lineImageView setImage:lineImage];
    [self.viewContainer addSubview:lineImageView];
    [lineImageView release];
    
    UIImageView *textImageView = [[UIImageView alloc]initWithFrame:CGRectMake(13, 77, 294, 84)];
    textImageView.backgroundColor = [UIColor clearColor];
    UIImage *textImage = [UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:kFormImageFile ofType:nil]];
    textImage = [textImage resizableImageWithCapInsets:UIEdgeInsetsMake(3, 3, 3, 3)];
    [textImageView setImage:textImage];
    textImageView.userInteractionEnabled = YES;
    
    _contentTextView = [[UITextView alloc]initWithFrame:textImageView.bounds];
    _contentTextView.backgroundColor = [UIColor clearColor];
    _contentTextView.delegate = self;
    _contentTextView.textColor = [UIColor colorWithHex:0xff989797];
    _contentTextView.font = [UIFont fontWithName:kFontNameLightHeiti size:12];
    [_contentTextView setReturnKeyType:UIReturnKeyDone];
    _contentTextView.text = kTextViewHolderStr;
    
    [textImageView addSubview:_contentTextView];

    _wordCountLabel = [[UILabel alloc]initWithFrame:CGRectMake(265,60,25,12)];
    _wordCountLabel.backgroundColor = [UIColor clearColor];
    _wordCountLabel.textColor = [UIColor colorWithHex:0xff979797];
    _wordCountLabel.font = [UIFont fontWithName:kFontNameHelvetica size:12];
    _wordCountLabel.text = @"600";
    [textImageView addSubview:_wordCountLabel];
    
    
    [self.viewContainer addSubview:textImageView];
    [textImageView release];
    
        
    
    
    UILabel *emailLabel = [[UILabel alloc]initWithFrame:CGRectMake(25, 188, 50, 16)];
    emailLabel.backgroundColor = [UIColor clearColor];
    emailLabel.textColor = [UIColor colorWithHex:0xff979797];
    emailLabel.font = [UIFont fontWithName:@"Arial" size:16];
    emailLabel.text = @"Email";
    [self.viewContainer addSubview:emailLabel];
    [emailLabel release];
    
    UIImageView *textFiledImageView = [[UIImageView alloc]initWithFrame:CGRectMake(76, 176, 228, 40)];
    textFiledImageView.backgroundColor = [UIColor clearColor];
    textFiledImageView.userInteractionEnabled = YES;
    UIImage *textFiledImage = [UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:kFormImageFile ofType:nil]];
    textFiledImage = [textFiledImage resizableImageWithCapInsets:UIEdgeInsetsMake(3, 3, 3, 3)];
    [textFiledImageView setImage:textFiledImage];
    
    _contentTextField = [[UITextField alloc]initWithFrame:CGRectMake(8, 0, 220, 40)];
    _contentTextField.backgroundColor = [UIColor clearColor];
    _contentTextField.delegate = self;
    _contentTextField.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter;
    _contentTextField.textColor = [UIColor colorWithHex:0xff979797];
    _contentTextField.font = [UIFont fontWithName:kFontNameLightHeiti size:12];
    [_contentTextField setReturnKeyType:UIReturnKeyDone];
    [textFiledImageView addSubview:_contentTextField];
    
    
    [self.viewContainer addSubview:textFiledImageView];
    [textFiledImageView release];
    
    
    
    
    _commitButton = [[UIButton alloc]initWithFrame:CGRectMake(13, 245, 293, 35)];
    _commitButton.backgroundColor = [UIColor clearColor];
    [_commitButton setBackgroundImage:[UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:kButtonImageFile ofType:nil]] forState:UIControlStateNormal];
    [_commitButton setBackgroundImage:[UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:kButtonImageFile ofType:nil]] forState:UIControlStateHighlighted];
    _commitButton.titleLabel.font = [UIFont fontWithName:kFontNameLightHeiti size:16];
    [_commitButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [_commitButton setTitleColor:[UIColor whiteColor] forState:UIControlStateHighlighted];
    [_commitButton setTitle:@"提交" forState:UIControlStateNormal];
    [_commitButton setTitle:@"提交" forState:UIControlStateHighlighted];
    [_commitButton addTarget:self action:@selector(commitButtonClicked) forControlEvents:UIControlEventTouchUpInside];
    _commitButton.enabled = NO;
    [self.viewContainer addSubview:_commitButton];
    
    
}

#pragma mark -
#pragma mark UITextView Delegate

- (BOOL)textViewShouldBeginEditing:(UITextView *)textView{
    if ([textView.text isEqualToString:kTextViewHolderStr]) {
        textView.text=@"";
    }
    
    return YES;
}


- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text{
    if ([text isEqualToString:@"\n"]) {
        [textView resignFirstResponder];
        return NO;
    }
    return YES;
}

- (void)textViewDidEndEditing:(UITextView *)textView{
    if ([textView.text isEqualToString:@""]) {
        textView.text = kTextViewHolderStr;
    }
}

- (void)textViewDidChange:(UITextView *)textView
{
    int length = 0;
    length = [textView.text length];
    _commitButton.enabled = YES;
    _rightButton.enabled = YES;
    NSInteger restCount = kMaxWordCount - length;
    _wordCountLabel.text = [NSString stringWithFormat:@"%d",restCount];
    if (length > kMaxWordCount) {
        _wordCountLabel.textColor = [UIColor redColor];
        _commitButton.enabled = NO;
       _rightButton.enabled = NO;
    }else if(length == 0){
        _wordCountLabel.textColor = [UIColor colorWithHex:0xff979797];
        _commitButton.enabled = NO;
        _rightButton.enabled = NO;
    }else{
        _wordCountLabel.textColor = [UIColor colorWithHex:0xff979797];
    }
    
}

#pragma -mark UITextFeildDelegate

-(BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{
    if ([string isEqualToString:@"\n"]) {
        [textField resignFirstResponder];
        return NO;
    }
    return YES;
}

-(void)commitButtonClicked{
    
    _rightButton.enabled = NO;
    _commitButton.enabled = NO;
    
    NetworkStatus status = [GloableEngineService sharedInstance].netWorkStatus;
    if (status == kNotReachable) {
        [RCAppDelegate alertWithNetworkError];
        _rightButton.enabled = YES;
        _commitButton.enabled = YES;
        return;
    }
    if (nil == _contentTextView.text || [_contentTextView.text isEqualToString:@""] || [_contentTextView.text isEqualToString:kTextViewHolderStr]) {
        [RCAppDelegate alertWithCustomizeString:@"没有填写任何错误哦！"];
        _rightButton.enabled = YES;
        _commitButton.enabled = YES;
        return;
    }
    
    NSString *email = _contentTextField.text;
    
    if (email != nil) {
        
        
        NSError * error = NULL;
        NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"^([a-zA-Z0-9_\\.\\-])+\\@(([a-zA-Z0-9\\-])+\\.)+([a-zA-Z0-9]{2,4})$" options:0 error:&error];
        NSTextCheckingResult * result = [regex firstMatchInString:email options:0 range:NSMakeRange(0, [email length])];
        if (!result || (regex.numberOfCaptureGroups + 1) != result.numberOfRanges) {
            [RCAppDelegate alertWithCustomizeString:@"邮箱名错误"];
            _rightButton.enabled = YES;
            _commitButton.enabled = YES;
            return;
        }else if (email.length > 40){
            [RCAppDelegate alertWithCustomizeString:@"邮箱名好像太长了哦"];
            _rightButton.enabled = YES;
            _commitButton.enabled = YES;
            return;
        }
    }
    
    
    _progressHub = [[MBProgressHUDEx alloc] initWithView:self.view
                                               TopHeight:0
                                        withBottomHeight:0
                                           withLeftWidth:0
                                          withRightWidth:0
                                    withExclusiveObjects:nil];
    _progressHub.delegate = self;
    _progressHub.labelText = @"提交中...";
    [self.view addSubview:_progressHub];
    [self.view bringSubviewToFront:_progressHub];
    [_progressHub show:YES];
    _requestID = [[IManager sharedInstance]requestSubmitError:self.merchantID withContent:_contentTextView.text withEmail:email withDelegate:self];

}

-(void)updateViewForSuccess:(IDataModel *)dataModel withRequestId:(int64_t)requestId{
    if (_requestID == requestId) {
        [_progressHub removeFromSuperview];
        [_progressHub release];
        _progressHub = nil;
        RCFeedbackDataModel *feedbackDataModel = (RCFeedbackDataModel *)dataModel;
        if (feedbackDataModel.errorNO == 0) {
            [RCAppDelegate alertWithCustomizeString:@"提交成功"];
            _rightButton.enabled = NO;
            _commitButton.enabled = NO;
            [self performSelector: @selector(leftButtonClicked) withObject: nil afterDelay: 1.5f];
        }else{
            [RCAppDelegate alertWithCustomizeString:@"提交失败，请稍后重试"];
            _rightButton.enabled = YES;
            _commitButton.enabled = YES;
        }
    }
}

-(void)updateViewForError:(NSError *)errorInfo withRequestId:(int64_t)requestId{
    if (_requestID == requestId) {
        [_progressHub removeFromSuperview];
        [_progressHub release];
        _progressHub = nil;
        [RCAppDelegate alertWithCustomizeString:@"提交失败，请稍后重试"];
        _rightButton.enabled = YES;
        _commitButton.enabled = YES;
    }
}

-(void)leftButtonClicked{
    [self.navigationController popViewControllerAnimated:YES];
}


#pragma mark -
#pragma mark Responding to keyboard events
- (void)keyboardWillShow:(NSNotification *)notification {
    
    NSDictionary *userInfo = [notification userInfo];
    NSValue *value = [userInfo objectForKey:UIKeyboardFrameEndUserInfoKey];
    CGRect keyboardRect = [value CGRectValue];
    
    CGFloat keyboardOriginY = UIScreenHeight-64-keyboardRect.size.height;
    //    if ([[[UIDevice currentDevice]systemVersion]floatValue] >=7.0f) {
    //        keyboardOriginY = keyboardRect.origin.y;
    //    }
    CGFloat buttonMaxY = CGRectGetMaxY(_contentTextField.superview.frame);
    CGFloat viewcontainOriginY = self.viewContainer.frame.origin.y;
    if (buttonMaxY + viewcontainOriginY + 5 > keyboardOriginY) {
        
        [UIView animateWithDuration:0.3f animations:^{
            CGFloat heightReduce = abs(buttonMaxY + viewcontainOriginY +5 - keyboardOriginY);
            CGRect rect = self.viewContainer.frame;
            rect.origin.y -= heightReduce;
            self.viewContainer.frame = rect;
        }];
        
    }
    
}

- (void)keyboardWillHide:(NSNotification *)notification
{
    [UIView animateWithDuration:0.3f animations:^{
        self.viewContainer.frame = self.view.bounds;
    }];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
